<?php
namespace App\Http\Controllers\Api\FlyGo;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Service\Pay\WxPayService;
use Illuminate\Support\Facades\Redis as Redis;
use App\Models\Bill\Bill;
use App\Models\Bill\BillPay;

class PayController extends Controller
{

    /**
     * 获取小程序微信支付参数
     * @param Request $request
     */
    public function weixinAppletPay( Request $request )
    {
        $bill_no = $request->input('bill_no');
        if (empty($bill_no)) {
            return response()->json(['code' => 10001, 'message' => '缺少bill_no参数']);
        }

        $mallID = $request->input('mallID');
        if (empty($mallID)) {
            return response()->json(['code' => 10001, 'message' => '缺少mallID参数']);
        }

        $session_id = $request->input('session_id');
        if (empty($session_id)) {
            return response()->json(['code' => 10002, 'message' => '缺少session_id参数']);
        }

        //用户登录信息
        $wx_applet_info = Redis::get('WX_APPLET_USER_' . $session_id);
        if (!$wx_applet_info) {
            return response()->json(['code' => 10003, 'message' => '会员登录已失效']);
        }
        $wx_applet_info = json_decode($wx_applet_info, true);

        $bill_master = Bill::find($bill_no);
        if (!$bill_master) {
            return response()->json(['code' => 10004, 'message' => '订单信息未找到']);
        }

        $pay_result = BillPay::where([
            'bill_no' => $bill_no,
            'type' => 2
        ])->first();
        if (!$pay_result) {
            return response()->json(['code' => 10006, 'message' => '订单支付信息未找到']);
        }

        //微信异步接收路径
        $notify_url = $request->getSchemeAndHttpHost() . '/onlinepay/weixin/notify';

        $params = [
            'out_trade_no' => $bill_no,
            'trade_type' => 'JSAPI',
            'payTypeID' => 50,
            'mallID' => $mallID,
            'body' => '非常购',
            'total_fee' => $pay_result->pay_amount,
            'pcustID' => $bill_master->pcustID,
            'type' => 1,
            'openId' => $wx_applet_info['openId'],
            'notify_url' => $notify_url
        ];

        $return_data = [];
        $WxPayService = new WxPayService($params);
        $wx_pay = $WxPayService->request();
        if ($wx_pay['code'] == 200) {
            $return_data = $wx_pay['data']['params'];
        }

        return response()->json(['code' => 200, 'message' => 'ok', 'data' => $return_data]);
    }

}